package cn.wolfcode.luowowo.wesite.until;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.wesite.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by LENOVO on 2019/8/9.
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //明确参数注入的类型
    //如果为true就支持,如果为false就不支持
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //需要同时满足类型,而且贴有@UserParam注解的才会使用自定义的参数解析器
        return methodParameter.hasParameterAnnotation(UserParam.class) &&methodParameter.getParameterType() == UserInfo.class;

    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String token = CookieUtil.getToken(request);

        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        return userInfo;

    }
}
